//
//  AppDelegate.m
//  App
//
//  Created by feidu on 2019/1/9.
//  Copyright © 2019 refuse. All rights reserved.
//

#import "AppDelegate.h"
#import "ViewController.h"
#import "AppDelegate+util.h"
#import "AvoidCrash.h"



@interface AppDelegate ()
@property (nonatomic, strong)NSString *urlString;

@end

@implementation AppDelegate

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
	[self addBugHandle];
	
//	[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(AppdelegateChange) name:@"AppdelegateChangeToWebView" object:nil];
	
	/// 引导页 广告页
	[self addAdvertisement];
	
	//检查应用程序版本
	[self openAPPStore];
	
	// 添加极光推送
	//    [self addJPushWithApplication:application Options:launchOptions ];
	
	/// 添加友盟推送
//	[self resigsstUmengPushLaunchingWithOptions:(NSDictionary *)launchOptions ];
	
	// 高德地图
//	[AMapServices sharedServices].apiKey = @"722769633fae00aa38b98ac129d26055";
//	[[AMapServices sharedServices] setEnableHTTPS:YES];
//	[[RCIM sharedRCIM] initWithAppKey:RONGCLOUD_IM_APPKEY];
	
//	dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(120 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
//		NSMutableArray *arary = [NSMutableArray array];
//		arary[0] = @":fdhsfij";
//		NSLog(@"%@", arary[125]);
//	});
	
	ViewController *controller = [[ViewController alloc] init];
	self.window = [[UIWindow alloc] initWithFrame:[UIScreen mainScreen].bounds];
	self.window.rootViewController = [[UINavigationController alloc] initWithRootViewController:controller];
	return YES;
}

#pragma mark  添加 crash 处理机制
- (void)addBugHandle {
	[AvoidCrash becomeEffective]; //【默认不开启  对”unrecognized selector sent to instance”防止崩溃的处理】
	// 若要开启对对”unrecognized selector sent to instance”防止崩溃的处理】，请使用
	// [AvoidCrash makeAllEffective],使用注意点，请看AvoidCrash.h中的描述，必须配合[AvoidCrash setupNoneSelClassStringsArr:]的使用
	// 【建议在didFinishLaunchingWithOptions最初始位置调用】[AvoidCrash makeAllEffective]
	
	/*
	 [AvoidCrash becomeEffective]和[AvoidCrash makeAllEffective]是全局生效。若你只需要部分生效，你可以单个进行处理，比如:
	 [NSArray avoidCrashExchangeMethod];
	 [NSMutableArray avoidCrashExchangeMethod];
	 .................
	 .................
	 */
	
	//监听通知:AvoidCrashNotification, 获取AvoidCrash捕获的崩溃日志的详细信息
	[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(dealwithCrashMessage:) name:AvoidCrashNotification object:nil];
	
	// ICP 项目
	// app_id:3840c5257c     app_key:d08079fa-4083-425a-bf31-31d731413aa9
	[Bugly startWithAppId:@"3840c5257c"];
	
	
	dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(120 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
		NSArray *arary = [NSArray array];
		NSLog(@"%@", arary[1]);
	});
}

- (void)dealwithCrashMessage:(NSNotification *)note {
	//注意:所有的信息都在userInfo中
	//你可以在这里收集相应的崩溃信息进行相应的处理(比如传到自己服务器)
	NSDictionary *info = note.userInfo;
	NSString *errorReason = [NSString stringWithFormat:@"【ErrorReason】>>%@<<========【ErrorPlace】>>%@<<========【DefaultToDo】>>%@<<========【ErrorName】>>%@<<", info[@"errorReason"], info[@"errorPlace"], info[@"defaultToDo"], info[@"errorName"]];
	[Bugly reportException:[NSException exceptionWithName:@"user_default_error" reason:errorReason userInfo:info]];
	
//	NSArray *callStack = info[@"callStackSymbols"];
//	[Bugly reportExceptionWithCategory:3 name:info[@"errorName"] reason:errorReason callStack:callStack extraInfo:info terminateApp:NO];
	NSLog(@"%@",note.userInfo);
}
#pragma mark ending Crash handle



- (void) addAdvertisement {
	
	//#if 0
	//    if ([current_version() compare:prev_version()] == NSOrderedDescending) {
	//        KSGuaidManager.images = @[[UIImage imageNamed:@"guid01"],
	//                                  [UIImage imageNamed:@"guid02"],
	//                                  [UIImage imageNamed:@"guid03"],
	//                                  [UIImage imageNamed:@"guid04"]];
	//
	//        /*
	//         方式一:
	//
	//         CGSize size = [UIScreen mainScreen].bounds.size;
	//
	//         KSGuaidManager.dismissButtonImage = [UIImage imageNamed:@"hidden"];
	//
	//         KSGuaidManager.dismissButtonCenter = CGPointMake(size.width / 2, size.height - 80);
	//         */
	//
	//        //方式二:
	//        KSGuaidManager.shouldDismissWhenDragging = YES;
	//        [KSGuaidManager begin];
	//    } else {
	//        /// 广告页
	//        JYJPromotionPageViewController *con = [[JYJPromotionPageViewController alloc] init];
	//        __weak typeof(self) weakSelf = self;
	//        con.promotionPageViewBlock = ^{
	//            weakSelf.window.rootViewController = [ViewController new];
	//        };
	//        self.window.rootViewController = con;
	//    }
	//#else
	//    /// 广告页
	//    JYJPromotionPageViewController *con = [[JYJPromotionPageViewController alloc] init];
	//    __weak typeof(self) weakSelf = self;
	//    con.promotionPageViewBlock = ^{
	//        weakSelf.window.rootViewController = [ViewController new];
	//    };
	//    self.window.rootViewController = con;
	//
	//#endif
	//
	//	KSGuaidManager.images = @[[UIImage imageNamed:@"1"],
	//							  [UIImage imageNamed:@"2"],
	//							  [UIImage imageNamed:@"3"]];
	//	KSGuaidManager.shouldDismissWhenDragging = YES;
	//	KSGuaidManager.isAlwaysShow = YES; /// 是否一直显示引导页 默认更新显示
	//	KSGuaidManager.pageIndicatorTintColor = [UIColor clearColor];
	//
	//	KSGuaidManager.currentPageIndicatorTintColor = [UIColor clearColor];
	//
	//	[KSGuaidManager begin];
	
}

- (void)openAPPStore {
	NSString *urlStr = GoAppStoreUrl;
	NSMutableDictionary *postDic = [NSMutableDictionary dictionary];
	
	AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
	[manager GET:urlStr parameters:postDic progress:^(NSProgress * _Nonnull downloadProgress) {
	} success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
		NSLog(@"%@", responseObject);
		NSDictionary *dict = (NSDictionary *)responseObject;
		NSString *app_Version = [[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleShortVersionString"];
		if ( [dict[@"status"] intValue] == 0 && [[NSString stringWithFormat:@"%@", dict[@"data"][@"is_show"]] integerValue] == 1 ) {
			if (![dict[@"data"][@"version_name"] isEqualToString:app_Version]) {
				self.urlString = [NSString stringWithFormat:@"%@", dict[@"data"][@"update_url"]];
				UIAlertView *alert = [[UIAlertView alloc] initWithTitle:nil message:dict[@"data"][@"update_content"] delegate:self cancelButtonTitle:nil otherButtonTitles:@"去更新", nil];
				[alert show];
			}
		}
	} failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
		NSLog(@"%@", error);
	}];
}

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex {
	NSString *url = [NSString stringWithFormat:@"%@", GoAppStore];
	if (self.urlString && self.urlString.length > 7) {
		url = self.urlString;
	}
	NSString* encodedString = [url stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
	[[UIApplication sharedApplication ] openURL: [NSURL URLWithString:encodedString]];
	
	dispatch_time_t time=dispatch_time(DISPATCH_TIME_NOW, 4 * NSEC_PER_SEC);
	dispatch_after(time, dispatch_get_main_queue(), ^{
		exit(0);
	});
}



- (void)applicationWillResignActive:(UIApplication *)application {
	// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
	// Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game.
}


- (void)applicationDidEnterBackground:(UIApplication *)application {
	// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
	// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}


- (void)applicationWillEnterForeground:(UIApplication *)application {
	// Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background.
}


- (void)applicationDidBecomeActive:(UIApplication *)application {
	// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}


- (void)applicationWillTerminate:(UIApplication *)application {
	// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}


//- (BOOL)application:(UIApplication *)app openURL:(NSURL *)url options:(NSDictionary<NSString*, id> *)options
//{
//	if ([url.host isEqualToString:@"safepay"]) {
//		// 支付跳转支付宝钱包进行支付,处理支付结果
//		[[AlipaySDK defaultService] processOrderWithPaymentResult:url standbyCallback:^(NSDictionary *resultDic) {
//			NSLog(@"result = %@",resultDic);
//		}];
//		// 授权跳转支付宝钱包进行支付,处理支付结果
//		[[AlipaySDK defaultService] processAuth_V2Result:url standbyCallback:^(NSDictionary *resultDic) {
//			NSLog(@"result = %@",resultDic);
//			// 解析 auth code
//			NSString *result = resultDic[@"result"];
//			NSString *authCode = nil;
//			if (result.length>0) {
//				NSArray *resultArr = [result componentsSeparatedByString:@"&;"];
//				for (NSString *subResult in resultArr) {
//					if (subResult.length > 10 && [subResult hasPrefix:@"auth_code="]) {
//						authCode = [subResult substringFromIndex:10];
//						break;
//					}
//				}
//			}
//			NSLog(@"授权结果 authCode = %@", authCode?:@"");
//		}];
//	}
//	return YES;
//}
//
//
//
//- (BOOL)application:(UIApplication *)application openURL:(NSURL *)url sourceApplication:(NSString *)sourceApplication annotation:(id)annotation {
//	
//	//如果极简开发包不可用，会跳转支付宝钱包进行支付，需要将支付宝钱包的支付结果回传给开发包
//	if ([url.host isEqualToString:@"safepay"]) {
//		[[AlipaySDK defaultService] processOrderWithPaymentResult:url standbyCallback:^(NSDictionary *resultDic) {
//			//【由于在跳转支付宝客户端支付的过程中，商户app在后台很可能被系统kill了，所以pay接口的callback就会失效，请商户对standbyCallback返回的回调结果进行处理,就是在这个方法里面处理跟callback一样的逻辑】
//			//			NSLog(@"result = %@",resultDic);
//		}];
//	}
//	if ([url.host isEqualToString:@"platformapi"]){//支付宝钱包快登授权返回authCode
//		
//		[[AlipaySDK defaultService] processAuthResult:url standbyCallback:^(NSDictionary *resultDic) {
//			//【由于在跳转支付宝客户端支付的过程中，商户app在后台很可能被系统kill了，所以pay接口的callback就会失效，请商户对standbyCallback返回的回调结果进行处理,就是在这个方法里面处理跟callback一样的逻辑】
//			NSLog(@"result = %@",resultDic);
//		}];
//	}
//	return YES;
//}

@end
